#include "app_gpio.h"

#define HC32595DATA GPIO_PIN_00 //PA0 
#define HC32595STCP GPIO_PIN_01 //PA1 
#define HC32595SHCP GPIO_PIN_13 //PC13
#define HC324067D0  GPIO_PIN_05 //PB5
#define HC324067D1  GPIO_PIN_08 //PB8
#define HC324067D2  GPIO_PIN_09 //PB9
#define HC324067D3  GPIO_PIN_10 //PA11
#define HC324067D4  GPIO_PIN_08 //PA8
#define HC324067D5  GPIO_PIN_15 //PB15
#define HC324067D6  GPIO_PIN_13 //PB13
#define HC324067D7  GPIO_PIN_14 //PB14
#define HC324067EN1 GPIO_PIN_11 //PB11
#define HC324067EN2 GPIO_PIN_12 //PB12

#define HC32595DATAPORT GPIO_PORT_A  //PA0  
#define HC32595STCPPORT GPIO_PORT_A  //PA1  
#define HC32595SHCPPORT GPIO_PORT_C  //PC13
#define HC324067D0PORT  GPIO_PORT_B  //PB5
#define HC324067D1PORT  GPIO_PORT_B  //PB8
#define HC324067D2PORT  GPIO_PORT_B  //PB9
#define HC324067D3PORT  GPIO_PORT_B  //PB10
#define HC324067D4PORT  GPIO_PORT_A  //PA8
#define HC324067D5PORT  GPIO_PORT_B  //PB15
#define HC324067D6PORT  GPIO_PORT_B  //PB13
#define HC324067D7PORT  GPIO_PORT_B  //PB14
#define HC324067EN1PORT GPIO_PORT_B  //PB11
#define HC324067EN2PORT GPIO_PORT_B  //PB12

#define HC32TESTLED     GPIO_PIN_06 //PB6
#define HC32TESTLEDPORT GPIO_PORT_B //PB6

#define HC32TESTLEDA0     GPIO_PIN_00 //PB6
#define HC32TESTLEDPORTA0 GPIO_PORT_E //PB6

#define KEYIN_PORT        (GPIO_PORT_B)
#define KEYIN_PIN         (GPIO_PIN_07)


#define portTICK_PERIOD_MS			( ( TickType_t ) 1000 / configTICK_RATE_HZ )

#define PB7_PORT              (GPIO_PORT_B)
#define PB7_PIN               (GPIO_PIN_07)
#define PB7_EXTINT_CH         (EXTINT_CH07)
#define PB7_INT_SRC           (INT_SRC_PORT_EIRQ7)
#define PB7_GLB_INT_IRQn      (INT008_IRQn)   // 全局中断号
#define PB7_INT_PRIO          (DDL_IRQ_PRIO_DEFAULT)

/* TMR0 unit and channel definition */
// #define TMR0_UNIT                       (CM_TMR0_1)
// #define TMR0_CLK                        (FCG2_PERIPH_TMR0_1)
// #define TMR0_CH                         (TMR0_CH_B)
// #define TMR0_TRIG_CH                    (AOS_TMR0)
// #define TMR0_CH_INT                     (TMR0_INT_CMP_B)
// #define TMR0_CH_FLAG                    (TMR0_FLAG_CMP_B)
// #define TMR0_INT_SRC                    (INT_SRC_TMR0_1_CMP_B)
// #define TMR0_IRQn                       (INT006_IRQn)


#define TMR2_UNIT                       (CM_TMR2_1)
#define TMR2_CH                         (TMR2_CH_A)
#define TMR2_PERIPH_CLK                 (FCG2_PERIPH_TMR2_1)
#define TMR2_CLK_SRC                    (TMR2_CLK_PCLK1)
#define TMR2_CLK_DIV                    (TMR2_CLK_DIV4)
#define TMR2_CMP_VAL                    (19999UL) // 每1ms触发一次中断

/* Definitions about Timer2 interrupt for the example. */
#define TMR2_INT_TYPE                   (TMR2_INT_MATCH_CH_A)
#define TMR2_INT_PRIO                   (DDL_IRQ_PRIO_03)
#define TMR2_INT_SRC                    (INT_SRC_TMR2_1_CMP_A)
#define TMR2_INT_IRQn                   (INT050_IRQn)
#define TMR2_FLAG                       (TMR2_FLAG_MATCH_CH_A)


/* Long press time: 5 seconds */
#define LONG_PRESS_TIME_MS              (5000U) // 长按时间：5000ms


/* Period = 1 / (Clock freq / div) * (Compare value + 1) = 1ms */
#define XTAL32_VALUE                    (32768UL)
#define TMR0_CMP_VALUE                  (XTAL32_VALUE / 4U / 1000U - 1U) /* 1ms interval */




/*! Parameter validity check for port source. */
#define IS_GPIO_PORT(port)                                                      \
(   ((port) == GPIO_PORT_A)                     ||                              \
    ((port) == GPIO_PORT_B)                     ||                              \
    ((port) == GPIO_PORT_C)                     ||                              \
    ((port) == GPIO_PORT_D)                     ||                              \
    ((port) == GPIO_PORT_E)                     ||                              \
    ((port) == GPIO_PORT_F)                     ||                              \
    ((port) == GPIO_PORT_G)                     ||                              \
    ((port) == GPIO_PORT_H)                     ||                              \
    ((port) == GPIO_PORT_I))


/*! Parameter validity check for pin number. */
#define IS_GPIO_PIN(pin)                                                        \
(   ((pin) != 0U)                               &&                              \
    (((pin) & GPIO_PIN_ALL) != 0U))


    //定时器模块
static volatile uint32_t timer_count = 0;
static volatile uint8_t isKeyPressed = 0;    
uint8_t spurious_count = 0;

//清除误触标志位
void set_spurious_count(void)
{
    spurious_count = 0;
}



//定时器
static void TMR2_Cmp_IrqCallback(void);
static void EXTINT_PB7_IrqCallback(void);

// void create_freertos_tasks(void);
/**
 * @brief  设置指定 GPIO 引脚的电平
 * @param  [in] u8Port: GPIO_PORT_x, x 可以是 @ref GPIO_Port_Source 中每个产品的后缀
 * @param  [in] u16Pin: GPIO_PIN_x, x 可以是 @ref GPIO_Pins_Define 中每个产品的后缀
 * @param  [in] num: 电平值，1 表示高电平，0 表示低电平
 * @retval None
 */
void gpio_set_level(uint8_t u8Port, uint16_t u16Pin, int num)
{
    if (1 == num) {
        GPIO_SetPins(u8Port, u16Pin);
    } else if (0 == num) {
        GPIO_ResetPins(u8Port, u16Pin);
    }
}


/**
 * @brief 获取一个整数指定位置的二进制位的值
 * @param num 要操作的整数
 * @param bit 要获取的二进制位的位置，从 0 开始计数
 * @return 指定位置的二进制位的值，0 或 1
//  */
uint8_t GETBIT(uint32_t num, uint8_t bit) {
    return (num >> bit) &1;
}
// #define  GETBIT(data, bit)   ((data>>bit)&1)


/// @brief ////hc595 send 4 byte
/// @param byte /
void hc595Send4Byte(uint32_t byte)
{
    //1
	//1 SHCP 移位信号
    //2 STCP 寄存器锁存信号
    //3 raise date trans
    gpio_set_level(HC32595STCPPORT,HC32595STCP,0);// gpio_set_level(ESP32_595STCP,0);
	for(int i=0;i<32;i++){
		gpio_set_level(HC32595SHCPPORT,HC32595SHCP,0);//gpio_set_level(ESP32_595SHCP,0);
		uint32_t data = (byte<<i)&0x80000000;
		if(data){
			gpio_set_level(HC32595DATAPORT,HC32595DATA,1);//gpio_set_level(ESP32_595DATA,1);
		}else{
			gpio_set_level(HC32595DATAPORT,HC32595DATA,0);//gpio_set_level(ESP32_595DATA,0);
		}			
		gpio_set_level(HC32595SHCPPORT,HC32595SHCP,1);//gpio_set_level(ESP32_595SHCP,1);
	}
	gpio_set_level(HC32595STCPPORT,HC32595STCP,1);//gpio_set_level(ESP32_595STCP,1);
}

void hc4067Chose1Channel32(uint8_t channel)//21 choose 1  channel(0~31)
{
	//if(channel>31)assert(0);
	if(channel<16){
		channel = channel ;
		gpio_set_level(HC324067EN1PORT,HC324067EN1,0);//choose 4067 en  gpio_set_level(ESP32_4067EN1,0);
		gpio_set_level(HC324067EN2PORT,HC324067EN2,1);//gpio_set_level(ESP32_4067EN2,1);	
		gpio_set_level(HC324067D0PORT,HC324067D0,GETBIT(channel, 0));//gpio_set_level(ESP32_4067D0,GETBIT(channel, 0));
		gpio_set_level(HC324067D1PORT,HC324067D1,GETBIT(channel, 1));//gpio_set_level(ESP32_4067D1,GETBIT(channel, 1));
		gpio_set_level(HC324067D2PORT,HC324067D2,GETBIT(channel, 2));//gpio_set_level(ESP32_4067D2,GETBIT(channel, 2));
		gpio_set_level(HC324067D3PORT,HC324067D3,GETBIT(channel, 3));//gpio_set_level(ESP32_4067D3,GETBIT(channel, 3));
		//printf("<%d><%d><%d><%d>\n",GETBIT(channel, 0),GETBIT(channel, 1),GETBIT(channel, 2),GETBIT(channel, 3));
	}else{
		channel = channel - 16;
		gpio_set_level(HC324067EN1PORT,HC324067EN1,1);//choose 4067 en  gpio_set_level(ESP32_4067EN1,1);
		gpio_set_level(HC324067EN2PORT,HC324067EN2,0);//gpio_set_level(ESP32_4067EN2,0);
		gpio_set_level(HC324067D4PORT,HC324067D4,GETBIT(channel, 0));//gpio_set_level(ESP32_4067D4,GETBIT(channel, 0));
		gpio_set_level(HC324067D5PORT,HC324067D5,GETBIT(channel, 1));//gpio_set_level(ESP32_4067D5,GETBIT(channel, 1));
		gpio_set_level(HC324067D6PORT,HC324067D6,GETBIT(channel, 2));//gpio_set_level(ESP32_4067D6,GETBIT(channel, 2));
		gpio_set_level(HC324067D7PORT,HC324067D7,GETBIT(channel, 3));//gpio_set_level(ESP32_4067D7,GETBIT(channel, 3));
	}
	
}

//////////////////////////////LED部分


int currentLedStatus = LED_STATUS_ON;

uint8_t Get_LED_State(void)
{
    return currentLedStatus;
}

void Set_LED_State(uint8_t state)
{
    currentLedStatus = state;
}
// 初始化 LED 引脚
void Led_Init(void)
{
    stc_gpio_init_t stcGpioInit;

     // 根据头文件定义设置引脚状态
     stcGpioInit.u16PinState = PIN_STAT_SET;  
     // 设置引脚方向为输出
     stcGpioInit.u16PinDir = PIN_DIR_OUT;  
     // 设置输出类型为 CMOS
     stcGpioInit.u16PinOutputType = PIN_OUT_TYPE_CMOS;  
     // 设置驱动能力为低
     stcGpioInit.u16PinDrv = PIN_LOW_DRV;  
     // 禁用锁存
     stcGpioInit.u16Latch = PIN_LATCH_OFF;  
     // 禁用上拉电阻
     stcGpioInit.u16PullUp = PIN_PU_ON;  
     // 禁用翻转
     stcGpioInit.u16Invert = PIN_INVT_OFF;  
     // 禁用外部中断
     stcGpioInit.u16ExtInt = PIN_EXTINT_OFF;  
     // 设置输入类型为 SMT
     stcGpioInit.u16PinInputType = PIN_IN_TYPE_SMT;  
     // 设置引脚属性为数字
     stcGpioInit.u16PinAttr = PIN_ATTR_DIGITAL;  
    (void)GPIO_Init(HC32TESTLEDPORT, HC32TESTLED, &stcGpioInit);
}


// static int firsttimepress = 0;
// int confignetstep = 0;

// int gpiotestflag = 0;
// int timecount = 0;

// void KeyRow1_Callback(void)
// {
    // // static int confignet_step = 0;
    // // static int longpresstime = 0;
    // if (SET == EXTINT_GetExtIntStatus(EXTINT_CH00))
    // {
    //     if (0 == GPIO_ReadInputPins(KEYIN_PORT, KEYIN_PIN)) { // key press
            
    //         firsttimepress = timecount;
    //         GPIO_ResetPins(HC32TESTLEDPORTA0 , HC32TESTLEDA0 );
            
    //     }
    //     else { // key up
    //         GPIO_SetPins(HC32TESTLEDPORTA0 , HC32TESTLEDA0 );
    //         gpiotestflag = 1;
    //         if (confignetstep == 1) {
    //             if ((timecount - firsttimepress) < 100) {
                    
    //                 Set_LED_State(LED_STATUS_QUICK_BLINK);// 使用枚举类型
    //                 // gpio_handle.start_netconfig_flag = 1;
    //             }
    //             else {
    //                 Set_LED_State(LED_STATUS_ON); // 使用枚举类型
    //             }
    //             confignetstep = 0;
    //             firsttimepress = 0;
    //         }
    //     }
    // }
    // EXTINT_ClearExtIntStatus(EXTINT_CH00);
    // NVIC_DisableIRQ(INT007_IRQn);
    // NVIC_EnableIRQ(INT007_IRQn);
// }



/**
 * @brief  KEY Row1 global IT initialize
 * @param  None
 * @retval None
 */
// static void KeyRow1_Init(void)
// {
//     stc_extint_init_t stcExtIntInit;
//     // stc_irq_signin_config_t stcIrqSignConfig;
//     stc_gpio_init_t stcGpioInit;


//     /* GPIO config */
//     (void)GPIO_StructInit(&stcGpioInit);
//     stcGpioInit.u16ExtInt = PIN_EXTINT_ON;
//     stcGpioInit.u16PullUp = PIN_PU_ON;
//     stcGpioInit.u16PinDir = PIN_DIR_IN;       // 输入模式
//     (void)GPIO_Init(KEYIN_PORT, KEYIN_PIN, &stcGpioInit);

//     /* ExtInt config */
//     (void)EXTINT_StructInit(&stcExtIntInit);
//     stcExtIntInit.u32Filter      = EXTINT_FILTER_ON;
//     stcExtIntInit.u32FilterClock = EXTINT_FCLK_DIV8;
//     stcExtIntInit.u32Edge = EXTINT_TRIG_FALLING; // 双边沿触发，对应原代码 ExIntBothEdge
//     (void)EXTINT_Init(EXTINT_CH07, &stcExtIntInit);

//     // /* IRQ sign-in */
//     // stcIrqSignConfig.enIntSrc = INT_SRC_PORT_EIRQ7;
//     // stcIrqSignConfig.enIRQn   = INT007_IRQn;
//     // stcIrqSignConfig.pfnCallback = &KeyRow1_Callback;
//     // (void)INTC_IrqSignIn(&stcIrqSignConfig);


//     // /* NVIC config */
//     // NVIC_ClearPendingIRQ(stcIrqSignConfig.enIRQn);
//     // NVIC_SetPriority(stcIrqSignConfig.enIRQn, DDL_IRQ_PRIO_00);
//     // NVIC_EnableIRQ(stcIrqSignConfig.enIRQn);
// }


void App_init_gpio(void)
{
    stc_gpio_init_t stcGpioInit;
    (void)GPIO_StructInit(&stcGpioInit);

    // 统一配置为推挽输出模式
    stcGpioInit.u16PinDir = PIN_DIR_OUT;
    stcGpioInit.u16PinOutputType = PIN_OUT_TYPE_CMOS;
    stcGpioInit.u16PinDrv = PIN_HIGH_DRV; // 提高驱动能力

    /* 初始化595控制引脚 */
    (void)GPIO_Init(HC32595DATAPORT, HC32595DATA, &stcGpioInit);
    (void)GPIO_Init(HC32595SHCPPORT, HC32595SHCP, &stcGpioInit);
    (void)GPIO_Init(HC32595STCPPORT, HC32595STCP, &stcGpioInit);

    /* 初始化4067控制引脚 */
    (void)GPIO_Init(HC324067D0PORT, HC324067D0, &stcGpioInit);
    /* 初始化其他D1-D7、EN1、EN2引脚... */
    (void)GPIO_Init(HC324067D1PORT, HC324067D1, &stcGpioInit);
    (void)GPIO_Init(HC324067D2PORT, HC324067D2, &stcGpioInit);
    (void)GPIO_Init(HC324067D3PORT, HC324067D3, &stcGpioInit);
    (void)GPIO_Init(HC324067D4PORT, HC324067D4, &stcGpioInit);
    (void)GPIO_Init(HC324067D5PORT, HC324067D5, &stcGpioInit);
    (void)GPIO_Init(HC324067D6PORT, HC324067D6, &stcGpioInit);
    (void)GPIO_Init(HC324067D7PORT, HC324067D7, &stcGpioInit);
    (void)GPIO_Init(HC324067EN1PORT, HC324067EN1, &stcGpioInit);
    (void)GPIO_Init(HC324067EN2PORT, HC324067EN2, &stcGpioInit);

    //A0LED
    // (void)GPIO_Init(HC32TESTLEDPORTA0, HC32TESTLEDA0, &stcGpioInit);
    
    // 测试LED初始化
    // (void)GPIO_Init(HC32TESTLEDPORT, HC32TESTLED, &stcGpioInit);

    // Led_Init();
    // GPIO_ResetPins(HC32TESTLEDPORTA0, HC32TESTLEDA0);
    // KeyRow1_Init();
    // Led_Init();
    // GPIO_SetPins(HC32TESTLEDPORT, HC32TESTLED);

    // create_freertos_tasks();
}

// void create_freertos_tasks(void)
// {
//     xTaskCreate((TaskFunction_t)gpio_timer,
//     (const char *)"gpio_timer",
//     (uint16_t)1000,
//     (void *)NULL,
//     (UBaseType_t)2,
//     NULL);

//     xTaskCreate((TaskFunction_t)led_task,
//     (const char *)"led_task",
//     (uint16_t)1000,
//     (void *)NULL,
//     (UBaseType_t)2,
//     NULL);
   
// }

GPIO_HANDLE gpio_handle = {	
	.init_gpio = App_init_gpio,
	.hc595Send4Byte = hc595Send4Byte,
	.hc4067Chose1Channel32 = hc4067Chose1Channel32,
	
};


// void gpio_timer(void *pvParameters)
// {
//     while (1) {
//         if (timecount > 0xfffffff0) {
//             timecount = 0;
//         }
//         timecount += 1;

//         if ((firsttimepress != 0) && (timecount - firsttimepress) == 50) {
//             if (0 == GPIO_ReadInputPins(KEYIN_PORT, KEYIN_PIN)) {
//                 // Set_LED_State(LED_STATUS_QUICK_BLINK);  // 使用枚举类型更新 LED 状态
//                 confignetstep = 1;
//                 timecount = 0;
//             } else {
//                 confignetstep = 0;
//                 firsttimepress = 0;
//             }
//         }
//         vTaskDelay(100 / portTICK_PERIOD_MS);  // 修正延时调用，使用 portTICK_PERIOD_MS
//     }
// }


// LED 任务函数
void led_task(void *pvParameters)
{
    while (1) {
        switch (Get_LED_State()) {

            case LED_STATUS_OFF:
                GPIO_ResetPins(HC32TESTLEDPORT, HC32TESTLED);
                GPIO_ResetPins(HC32TESTLEDPORTA0, HC32TESTLEDA0);
                 vTaskDelay(200 / portTICK_PERIOD_MS);
                break;
            case LED_STATUS_ON:
                GPIO_SetPins(HC32TESTLEDPORT, HC32TESTLED);
                GPIO_SetPins(HC32TESTLEDPORTA0 , HC32TESTLEDA0 );
                 vTaskDelay(200 / portTICK_PERIOD_MS);
                break;
    
            case LED_STATUS_QUICK_BLINK:

                GPIO_SetPins(HC32TESTLEDPORT, HC32TESTLED);
                vTaskDelay(150 / portTICK_PERIOD_MS);
                GPIO_ResetPins(HC32TESTLEDPORT, HC32TESTLED);
                vTaskDelay(150 / portTICK_PERIOD_MS);
                break;

                case LED_STATUS_NETWORK:  // 呼吸灯模式
                GPIO_ResetPins(HC32TESTLEDPORT, HC32TESTLED);
                vTaskDelay(1000 / portTICK_PERIOD_MS);
                GPIO_SetPins(HC32TESTLEDPORT, HC32TESTLED);
                vTaskDelay(1000 / portTICK_PERIOD_MS);
                break;    
            default:
                break;
        }
       
        
    }
}

/**
 * @brief  PB7 External interrupt Ch.7 callback function
 * @param  None
 * @retval None
 */
// static void EXTINT_PB7_IrqCallback(void)
// {
//     if (SET == EXTINT_GetExtIntStatus(PB7_EXTINT_CH)) {

//         GPIO_ResetPins(HC32TESTLEDPORTA0 , HC32TESTLEDA0 );

//         while (PIN_RESET == GPIO_ReadInputPins(PB7_PORT, PB7_PIN)) {
//             ;  // 等待按键释放
//         }
//         EXTINT_ClearExtIntStatus(PB7_EXTINT_CH);  // 清除中断标志
//     }
// }

// static void EXTINT_PB7_IrqCallback(void)
// {
//     if (SET == EXTINT_GetExtIntStatus(PB7_EXTINT_CH)) {
//         if (PIN_RESET == GPIO_ReadInputPins(PB7_PORT, PB7_PIN)) {
//             // 按键按下
//             isKeyPressed = 1;
//             timer_count = 0; // 重置计数器
//             TMR0_Start(TMR0_UNIT, TMR0_CH); // 启动定时器
//         } else {
//             // 按键释放
//             isKeyPressed = 0;
//             TMR0_Stop(TMR0_UNIT, TMR0_CH); // 停止定时器
//         }
//         EXTINT_ClearExtIntStatus(PB7_EXTINT_CH);  // 清除中断标志
//     }
// }


/**
 * @brief  PB7 IT initialize
 * @param  None
 * @retval None
 */
void App_ExTPB7_Init(void)
{
    
    stc_extint_init_t stcExtIntInit;
    stc_irq_signin_config_t stcIrqSignConfig;
    stc_gpio_init_t stcGpioInit;

    /* GPIO config */
    (void)GPIO_StructInit(&stcGpioInit);
    stcGpioInit.u16ExtInt = PIN_EXTINT_ON;  // 开启外部中断功能
    stcGpioInit.u16PullUp = PIN_PU_ON;      // 上拉电阻开启
    (void)GPIO_Init(PB7_PORT, PB7_PIN, &stcGpioInit);

    /* ExtInt config */
    (void)EXTINT_StructInit(&stcExtIntInit);
    stcExtIntInit.u32Filter      = EXTINT_FILTER_ON;     // 滤波功能开启
    stcExtIntInit.u32FilterClock = EXTINT_FCLK_DIV8;     // 滤波时钟分频
    stcExtIntInit.u32Edge        = EXTINT_TRIG_FALLING;  // 下降沿触发
    (void)EXTINT_Init(PB7_EXTINT_CH, &stcExtIntInit);

    /* IRQ sign-in */
    stcIrqSignConfig.enIntSrc    = PB7_INT_SRC;         // 中断源选择
    stcIrqSignConfig.enIRQn      = PB7_GLB_INT_IRQn;    // 中断号
    stcIrqSignConfig.pfnCallback = &EXTINT_PB7_IrqCallback;
    (void)INTC_IrqSignIn(&stcIrqSignConfig);

    /* NVIC config */
    NVIC_ClearPendingIRQ(stcIrqSignConfig.enIRQn);      // 清除挂起位
    NVIC_SetPriority(stcIrqSignConfig.enIRQn, PB7_INT_PRIO);  // 设置优先级
    NVIC_EnableIRQ(stcIrqSignConfig.enIRQn);            // 使能中断
}




/**
 * @brief  Timer2 configuration.
 * @param  None
 * @retval None
 */
static void Tmr2Config(void)
{
    stc_tmr2_init_t stcTmr2Init;

    /* 1. Enable Timer2 peripheral clock. */
    FCG_Fcg2PeriphClockCmd(TMR2_PERIPH_CLK, ENABLE);

    /* 2. Set a default initialization value for stcTmr2Init. */
    (void)TMR2_StructInit(&stcTmr2Init);

    /* 3. Modifies the initialization values depends on the application. */
    stcTmr2Init.u32ClockSrc     = TMR2_CLK_SRC;
    stcTmr2Init.u32ClockDiv     = TMR2_CLK_DIV;
    stcTmr2Init.u32Func         = TMR2_FUNC_CMP;
    stcTmr2Init.u32CompareValue = TMR2_CMP_VAL;
    (void)TMR2_Init(TMR2_UNIT, TMR2_CH, &stcTmr2Init);
}

/**
 * @brief  Timer2 interrupt configuration.
 * @param  None
 * @retval None
 */
static void Tmr2IrqConfig(void)
{
    stc_irq_signin_config_t stcIrq;

    stcIrq.enIntSrc    = TMR2_INT_SRC;
    stcIrq.enIRQn      = TMR2_INT_IRQn;
    stcIrq.pfnCallback = &TMR2_Cmp_IrqCallback;
    (void)INTC_IrqSignIn(&stcIrq);

    NVIC_ClearPendingIRQ(stcIrq.enIRQn);
    NVIC_SetPriority(stcIrq.enIRQn, TMR2_INT_PRIO);
    NVIC_EnableIRQ(stcIrq.enIRQn);

    /* Enable the specified interrupts of Timer2. */
    TMR2_IntCmd(TMR2_UNIT, TMR2_INT_TYPE, ENABLE);
}

void App_Tmr2_Init(void){
    Tmr2Config();
    Tmr2IrqConfig();
    TMR2_Start(TMR2_UNIT, TMR2_CH);
    
}

//led  闪烁
void led_twinkle(void)
{
    GPIO_SetPins(HC32TESTLEDPORT, HC32TESTLED);
    DDL_DelayMS(100);
    GPIO_ResetPins(HC32TESTLEDPORT, HC32TESTLED);
}



/**
 * @brief  Timer2 counter comparison match interrupt callback function.
 * @param  None
 * @retval None
 */
static void TMR2_Cmp_IrqCallback(void)
{
    if (isKeyPressed && GPIO_ReadInputPins(PB7_PORT, PB7_PIN) == PIN_RESET) {
        // 如果按键仍然按下
        timer_count++;

        if(spurious_count == 1 && timer_count >= LONG_PRESS_TIME_MS){
            spurious_count = 0;
            gpio_handle.start_netconfig_flag = 1;
            // Set_LED_State(LED_STATUS_NETWORK);
            // 如果按键释放
            timer_count = 0;            // 清零计数器
            TMR2_Stop(TMR2_UNIT, TMR2_CH); // 停止定时器
        }else if (timer_count >= LONG_PRESS_TIME_MS) {
            // GPIO_SetPins(HC32TESTLEDPORTA0 , HC32TESTLEDA0 );  // 点亮绿色LED
    
            spurious_count++;
            set_net_count(0);
            // gpio_handle.start_netconfig_flag = 1;
            Set_LED_State(LED_STATUS_OFF);
            
            TMR2_Stop(TMR2_UNIT, TMR2_CH); // 停止定时器
            //黑灯闪烁
            led_twinkle();
        }
    }else {
            // 如果按键释放
            timer_count = 0;            // 清零计数器
            TMR2_Stop(TMR2_UNIT, TMR2_CH); // 停止定时器
    }
            TMR2_ClearStatus(TMR2_UNIT, TMR2_FLAG);
}



/**
 * @brief  PB7 External interrupt Ch.7 callback function
 * @param  None
 * @retval None
 */
static void EXTINT_PB7_IrqCallback(void)
{
    if (SET == EXTINT_GetExtIntStatus(PB7_EXTINT_CH)) {
        if (GPIO_ReadInputPins(PB7_PORT, PB7_PIN) == PIN_RESET) {
            // 按键按下
            isKeyPressed = 1;
            timer_count = 0; // 重置计数器
            TMR2_Start(TMR2_UNIT, TMR2_CH); // 启动定时器
        } else {
            // 按键释放
            isKeyPressed = 0;
            TMR2_Stop(TMR2_UNIT, TMR2_CH); // 停止定时器
        }
        EXTINT_ClearExtIntStatus(PB7_EXTINT_CH);  // 清除中断标志
    }
}

/////////////=================GPIO-initialize-End==/////////////////////////////////////////

